$NG.AllReady(function (page, { useAction, useBeforeClick, useValuesChange, useClick, useUpdateRow, subscribe, useUpdateRows }) {
    const mstform = $NG.getCmpApi("p_form_tssxsp_m")
    const dgrid3 = $NG.getCmpApi("p_form_tssxsp_d3")
    const dgrid3_bar = $NG.getCmpApi("toolbar_p_form_tssxsp_d3")
    const dgrid2 = $NG.getCmpApi("p_form_tssxsp_d2")
    const dgrid2_bar = $NG.getCmpApi("toolbar_p_form_tssxsp_d2")
    const getHeadValue = (str) => mstform.getItem(str).getValue()

    const config = {
        d1data: [],
        d2data: []
    }

    useUpdateRows(() => {
        const rows = dgrid3.getRows()
        let total_amt = 0
        rows.forEach(el => {
            el.u_fyxj1 = (Number(el.u_cl1) || 0) + (Number(el.u_jx1) || 0) + (Number(el.u_qtfy) || 0) + (Number(el.u_sj1) || 0)
            el.u_dydcbhtje = (Number(el.u_gcl) || 0) + (Number(el.u_dj) || 0)
            el.u_lr2 = (Number(el.u_dydcbhtje) || 0) - (Number(el.u_nfb2) || 0) - (Number(el.u_fyxj1) || 0)
            el.u_lr1 = (Number(el.u_lr2) || 0) / (Number(el.u_gcl) || 0)
            el.u_nfb2 = (Number(el.u_nfb1) || 0) * (Number(el.u_gcl) || 0)
            el.u_cl2 = (Number(el.u_cl1) || 0) * (Number(el.u_gcl) || 0)
            el.u_jx2 = (Number(el.u_jx1) || 0) * (Number(el.u_gcl) || 0)
            el.u_qtfy2 = (Number(el.u_qtfy) || 0) * (Number(el.u_gcl) || 0)
            el.u_sj2 = (Number(el.u_sj1) || 0) * (Number(el.u_gcl) || 0)
            el.u_fyxj2 = (Number(el.u_cl2) || 0) + (Number(el.u_jx2) || 0) + (Number(el.u_qtfy2) || 0) + (Number(el.u_sj2) || 0)
            el.u_hj= (Number(el.u_gcl) || 0) * (Number(el.u_dj) || 0)
            total_amt += (Number(el.u_nfb2) || 0)
        })
        mstform.getItem("u_gjfbjk").setValue(total_amt)
        dgrid3.refreshView()
    }, "p_form_tssxsp_d3")

    useUpdateRows(() => {
        const row = dgrid2.getRows()
        row.forEach(item => {
            if (item.u_log == '1') {
                console.log(`item`, config, item);
                $NG.message("当前行是导入数据不可修改！")
                const el = config.d1data.filter(it => {
                    if (it.u_sourceid == item.u_sourceid) {
                        return it
                    }
                })
                if (el.length == 1) {
                    const element = el[0]
                    for (let key in element) {
                        item[key] = element[key]
                    }
                    dgrid2.refreshView()
                }
                return
            }
        })
    }, "p_form_tssxsp_d2")

    dgrid2_bar.insert({
        id: "d1_myadd",
        text: "明细选择",
        iconCls: "icon-New"
    });

    dgrid3_bar.insert({
        id: "d2_myadd",
        text: "明细选择",
        iconCls: "icon-New"
    });

    useClick(() => {
        helpD1()
    }, "d1_myadd")

    useClick(() => {
        helpD2()
    }, "d2_myadd")

    function helpD1() {
        const phid = getHeadValue("u_fbxmchsbh")
        if (!phid) {
            $NG.alert("请先选择分包策划！")
            return
        }
        //自定义打开帮助
        $NG.external.openNGHelp({
            type: "NGMultipleHelp",//NGSingleHelp
            helpId: "fbch_d2",
            valueField: "phid",
            labelField: "u_fbxmmc",
            clientSqlFilter:
                `a.pphid = '${phid}'`
        }).then((data) => {
            // console.log(`data`,data,data.reduce);
            const arr = data.reduce((value, item) => {
                console.log(`item`, item);
                const el = item.origin
                const lock = dgrid2.getRows().some(it => it.u_sourceid == el.phid)
                if (lock) {
                    return value
                }
                value.push({
                    rel_key1: el.rel_key1,
                    u_fbxmmc: el.u_fbxmmc,
                    u_sourceid: el.phid,
                    u_log: "1"
                })
                return value
            }, [])
            config.d1data = [...config.d1data, ...arr]
            dgrid2.addRows(arr)
            //data:拿到帮助选中的数据
        })
    }

    function helpD2() {
        const row = dgrid2.getSelectedData()
        const phid = getHeadValue("u_fbxmchsbh")
        if (row.length == 0) {
            $NG.alert("请先中一条父明细！")
            return
        }
        if (!phid) return
        //自定义打开帮助
        $NG.external.openNGHelp({
            type: "NGMultipleHelp",//NGSingleHelp
            helpId: "fbch_d3",
            valueField: "phid",
            labelField: "s_tree_name",
            clientSqlFilter:
                `a.pphid = '${phid}' and a.rel_key1 = '${row[0].rel_key1}'`
        }).then((data) => {
            // console.log(`data`,data,data.reduce);
            let arr = data.reduce((value, item) => {
                console.log(`item`, item);
                const el = item.origin
                const lock = dgrid3.getRows().some(it => it.u_sourceid == el.phid)
                if (lock) {
                    return value
                }
                value.push({
                    rel_key1: el.rel_key1,
                    s_tree_no: el.s_tree_no,
                    s_tree_name: el.s_tree_name,
                    u_sourceid: el.phid,
                    u_dw: el.u_dw,
                    u_gcl: el.u_gcl,
                    u_dj: el.u_dj,
                    u_hj: el.u_hj,
                    u_nfb1: el.u_nfbje,
                    u_lr1: el.u_lr,
                    u_cl1: el.u_cl,
                    u_jx1: el.u_jx,
                    u_qtfy: el.u_qtfy,
                    u_sj1: el.u_sj,
                    u_fyxj1: el.u_fyxj,
                    u_cl2: el.u_clje,
                    u_qtfy2: el.u_qtfyje,
                    u_sj2: el.u_sjje,
                    u_fyxj2: el.u_fyxjje,
                    u_dydcbhtje: el.u_dydcbhtje,
                    u_lr2: el.u_lrje,
                    u_nfb2: el.u_nfb,
                    u_bz: el.u_bz,
                    s_tree_pid: el.s_tree_pid,
                    s_tree_id: el.s_tree_id,
                    u_dw_EXName: el.msname,
                    u_log: "1"
                })
                return value
            }, [])
            console.log(`arr1`, arr);
            arr = arrayToTree(arr, "s_tree_id", "s_tree_pid")
            console.log(`arr2`, arr);
            dgrid3.addRows(arr)
            //data:拿到帮助选中的数据
        })
    }

    // 转属性结构
    function arrayToTree(items, idField = "id", parentField = "parentId", childrenField = "children") {
        const map = {};
        const roots = [];

        // 先建立 id → item 的映射
        items.forEach(item => {
            map[item[idField]] = { ...item, [childrenField]: [] };
        });

        // 组装树
        items.forEach(item => {
            const parentId = item[parentField];
            if (parentId == null || parentId.length < 2 || parentField == '0') {
                // 根节点
                roots.push(map[item[idField]]);
            } else if (map[parentId]) {
                // 挂到父节点的 children 上
                map[parentId][childrenField].push(map[item[idField]]);
            }
        });

        return roots;
    }

})